package com.miloyu.modelnet.network

import com.miloyu.modelnet.cache.CacheInterceptor
import com.miloyu.modelnet.cache.EnhancedCacheInterceptor
import com.miloyu.modelnet.network.logging.Level
import com.miloyu.modelnet.network.logging.LoggingInterceptor
import com.miloyu.modelnet.network.service.IApiService
import com.miloyu.modelnet.network.tools.HeaderInterceptor
import com.miloyu.modelnet.network.tools.HttpsUtils
import com.miloyu.modelnet.network.tools.NullOnEmptyConverterFactory

import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.internal.platform.Platform
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory

import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @Author: YY
 * @Time: 2021/8/11
 * @Describe Retrofit 单例类, 实现网络请求
 */
class HttpClient private constructor() {

    var apiService: IApiService

    private object Holder {
        val INSTANCE = HttpClient()
    }

    companion object {
        // 服务端路径
//        var baseUrl = "http://192.168.1.23:8007"
        var baseUrl = "http://api.onemicowell.com"
        // 超时时间
        private const val DEFAULT_TIMEOUT = 30

        private lateinit var okHttpClient: OkHttpClient
        private lateinit var retrofit: Retrofit

        val instance by lazy { Holder.INSTANCE }

    }


    init {

        val sslParams = HttpsUtils.getSslSocketFactory()

        okHttpClient = OkHttpClient.Builder()
            .sslSocketFactory(sslParams.sSLSocketFactory!!, sslParams.trustManager!!)
            .addInterceptor(
                LoggingInterceptor.Builder()//构建者模式
                .loggable(true) //是否开启日志打印
                .setLevel(Level.BASIC) //打印的等级
                .log(Platform.INFO) // 打印类型
                .request("Request") // request的Tag
                .response("Response")// Response的Tag
                //.addHeader("log-header", "I am the log request header.")
                // 添加打印头, 注意 key 和 value 都不能是中文
                .build()
            )
            .addInterceptor(CacheInterceptor())
            .addInterceptor(EnhancedCacheInterceptor())
            .addInterceptor(HeaderInterceptor.Builder().build())
            .connectTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIMEOUT.toLong(), TimeUnit.SECONDS)
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            //设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
            .build()

        retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(NullOnEmptyConverterFactory())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(baseUrl)
            .build()
        apiService =  retrofit.create(IApiService::class.java)

    }


    fun <T> create(service: Class<T>?): T {
        if (service == null) {
            throw RuntimeException("Api service is null!")
        }
        return retrofit.create(service)
    }

}